//
//  SetViewController.m
//  LiWuShuo
//
//  Created by 袁小航 on 14/11/19.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SetViewController.h"
#import "Set.h"
#import "AboutUsViewController.h"
#import "BackMessageViewController.h"

@interface SetViewController ()<UITableViewDataSource, UITableViewDelegate>

//创建SetView
@property(nonatomic, retain) Set *setView;

//定义缓存
@property(nonatomic, assign) float cache;

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    设置navigation
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:240/255.0 green:59/255.0 blue:59/255.0 alpha:1];
    self.navigationController.navigationBar.translucent = NO;

    UILabel * setTitle = [[UILabel alloc]init];
    setTitle.text = @"更多";
    setTitle.textColor = [UIColor whiteColor];
    setTitle.font = [UIFont systemFontOfSize:16];
    setTitle.frame = CGRectMake(0, 0, 40, 30);
    self.navigationItem.titleView = setTitle;
    
//    设置背景颜色为白色
    self.view.backgroundColor = [UIColor whiteColor];
    
//    自定义完成按钮
    [self createCompleteButton];
    
//    创建SetView
    [self createSetView];
    
}
#pragma mark - 创建SetView
- (void)createSetView
{
    self.setView = [[Set alloc]initWithFrame:self.view.bounds];
    _setView.setTableView.delegate = self;
    _setView.setTableView.dataSource = self;
    [self.view addSubview:_setView];
}
#pragma mark - setTableView 的 delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    if (indexPath.section == 0) {
        cell.textLabel.text = @"清除缓存";
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"意见反馈";
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"关于我们";
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"检查版本";
            cell.detailTextLabel.text = @"V1.0";
        }
    }
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    return cell;
}
#pragma mark - row点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        NSString * str = [NSString stringWithFormat:@"您已经干掉%.1fM缓存！", self.cache];
        if (self.cache < 0.3) {
            str = @"<已清空全部缓存>";
        }
        
        UIAlertView * clearn = [[UIAlertView alloc]initWithTitle:@"清除缓存" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        
        [clearn show];
        [self.view addSubview:clearn];
        
        [self action:nil];
        self.cache = 0;
        [_setView.setTableView reloadData];
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
//            BackMessageViewController *backVC = [[BackMessageViewController alloc]init];
//            [self.navigationController pushViewController:backVC animated:YES];
            UIAlertView *backMessage = [[UIAlertView alloc]initWithTitle:@"反馈信息" message:@"我们的邮箱是‘iYouLiWu@163.com’      感谢您的反馈！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [backMessage show];
        } else if (indexPath.row == 1) {
            AboutUsViewController *aboutVC = [[AboutUsViewController alloc]init];
            [self.navigationController pushViewController:aboutVC animated:YES];
        } else if (indexPath.row == 2) {
            UIAlertView *versionAlert = [[UIAlertView alloc]initWithTitle:@"版本" message:@"您当前是最新版本！" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
            [versionAlert show];
        }
    }
}

#pragma mark - section数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
#pragma mark - head的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
#pragma mark - foot的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark - 自定义完成按钮
- (void)createCompleteButton
{
    UIButton *complete = [UIButton buttonWithType:UIButtonTypeCustom];
    [complete setTitle:@"完成" forState:UIControlStateNormal];
    complete.frame = CGRectMake(275, 5, 40, 30);
    [complete addTarget:self action:@selector(completeAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navigationController.navigationBar addSubview:complete];
}

#pragma mark - 完成按钮的响应事件
- (void)completeAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 清空缓存
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    //    NSLog(@"%.2f", folderSize/(1024.0*1024.0));
    return folderSize/(1024.0*1024.0);
}
- (void)action:(id)sender
{
    //彻底清除缓存第一种方法
    UIButton * button = sender;
    [button setTitle:@"清理完毕" forState:UIControlStateNormal];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
    //    NSLog(@"%@",str);
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
